package com.xiaotu.server.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xiaotu.common.model.SpiderLogModel;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.Mail;
import com.xiaotu.common.util.PropertiesUtil;
import com.xiaotu.common.util.ThreadPool;
import com.xiaotu.common.util.UUIDUtils;
import com.xiaotu.spider.SpiderFactory;

import net.sf.json.JSONObject;

/**
 * @类名 SpiderRunService
 * @日期 2017年5月19日
 * @作者 高海军
 * @功能 爬虫任务运行service
 */
@Service
public class SpiderRunService
{
	@Autowired
	private SpiderFactory factory;
	
	private static final String FILE_SERV_URL = "file.serv.url";
	
	public void runSpiderAndSend(final Map<String, Object> map,
			List<JSONObject> targetList) throws Exception
	{
		SpiderLogModel spiderLog = new SpiderLogModel();
		spiderLog.setSeriesNo(UUIDUtils.getStringUUID());
		spiderLog.setStartTime(System.currentTimeMillis());
		spiderLog.setJobNature(Constants.LogConstants.TASK_NATURE_HANDLE);
		
		map.put("fileName", System.currentTimeMillis() + ".csv");
		map.put(SpiderFactory.FINISHED_RUNNER, new Runnable()
		{
			@Override
			public void run()
			{
				ThreadPool.execute(new Runnable()
				{
					@Override
					public void run()
					{
						String content = map.get("content") + "<br/>文件地址："
								+ PropertiesUtil.getProperty(FILE_SERV_URL)
								+ map.get("fileName")
								+ "<br/>若文件无法下载，请与技术人员联系！";
						Mail.send(Mail.SMTP,
								PropertiesUtil.getProperty(Mail.USER),
								map.get("email") + StringUtils.EMPTY,
								map.get("subject") + StringUtils.EMPTY, content,
								PropertiesUtil.getProperty(Mail.USER),
								PropertiesUtil.getProperty(Mail.PASSWORD));// 爬虫任务执行失败或者未爬取到数据
					}
				});
			}
		});
		
		factory.runSpider(map, spiderLog, targetList);
	}
}
